package com.example.messenger;

import java.io.ByteArrayInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends Activity {
	public final static String EXTRA_MESSAGE = "Id intent";
	String view2 = "";
	
	public static final String USERNAME="";
	public static final String PASSWORD="";
	public static final String VIEW2="";
	String username="";
	String password="";
	boolean saveFlag = false;
	List<Messages> fullList;
	private static final String PHP_SEND = "http://softeng.cs.uwosh.edu/students/cs342g4/sendmessage.php";
	private static final String PHP_GET = "http://softeng.cs.uwosh.edu/students/cs342g4/getmessages.php";
	private static final String PHP_CHECK = "http://softeng.cs.uwosh.edu/students/cs342g4/checkmessages.php";
	private Timer updateTimer;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ArrayList<String> list = new ArrayList<String>();
		list.add("Saved Messages");
		list.add("New Messages");
		final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter<String> adapter =  new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list);
		spinner.setAdapter(adapter);
		//spinner.setO
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
                if(spinner.getSelectedItemPosition()==0){
                	view2="Saved";
                	populateSaved();
                }else if (spinner.getSelectedItemPosition() == 1){
                	view2="New";
                	populateNew();
                	
                }else{
                	view2="New";
                	populateNew();
                	
                }
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}

			
        });

		populateSaved();
		EditText searchbar = (EditText) findViewById(R.id.searchbar);
		searchbar.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence cs, int arg1, int arg2,
					int arg3) {
				if(cs.length()==0){
						MessagesAdapter ad = new MessagesAdapter(MainActivity.this,fullList);
						((ListView)findViewById(R.id.mainListView)).setAdapter(ad);

				} else{
					ArrayList<Messages> newList = new ArrayList<Messages>();
					for(int i=0;i<fullList.size();i++){
						if(fullList.get(i).getReciever().contains(cs)||
						   fullList.get(i).getSender()  .contains(cs)||
						   fullList.get(i).getMessage() .contains(cs)){
							newList.add(fullList.get(i));
						}
					}
					MessagesAdapter ad = new MessagesAdapter(MainActivity.this,newList);
					((ListView)findViewById(R.id.mainListView)).setAdapter(ad);
				}
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
			}
		});
        

		
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		
		new getLoginInfo().execute();
		
		EditText searchbar = (EditText) findViewById(R.id.searchbar);
		
		ListView list = (ListView) findViewById(R.id.mainListView);

		
		
		searchbar.clearFocus();
		
		list.requestFocus();
		
		updateTimer = new Timer();
		updateTimer.schedule(new TimerTask(){
			@Override
			public void run(){
				new CheckMessageTask().execute();
				Spinner spinner = (Spinner) findViewById(R.id.spinner1);
				if(spinner.getSelectedItemPosition() == 1){
					populateNew();
				}
			}
		}, 10000, 10000);
	}

	protected void onPause(){
		super.onPause();
		updateTimer.cancel();
		updateTimer.purge();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.action_send:
	        	sendMessage();
	        	return true;	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(MainActivity.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				MainActivity.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	
	//Get Login Info
	private class getLoginInfo extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MessengerDataSource mds2 = new MessengerDataSource(MainActivity.this);
			
			mds2.open();
			
			try {
				username = mds2.getUsername();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return username;
		}
		
		@Override
		protected void onPostExecute(String whatever) {
			if (username.equals("user")){
				Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				return;
			}
			else{
				return;
			}
		}
		
	}
	
	public void sendMessage(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);   

	    LinearLayout lila1= new LinearLayout(this);
	    lila1.setOrientation(1); 
	    final EditText to = new EditText(this); 
	    to.setHint("Username");
	    final EditText message = new EditText(this);
	    message.setHint("Message");
	    TextView SendMessage = new TextView(this);
	    TextView To = new TextView(this);
	    alert.setTitle("Send Message");  
	    To.setText("To :");
	    To.setTextSize(20);
	    To.setPadding(15,0,0,0);
	    SendMessage.setPadding(15,0,0,0);
	    SendMessage.setInputType(android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE);
	    SendMessage.setTextSize(20);
	    SendMessage.setText("Message :");
	    lila1.addView(To);
	    lila1.addView(to);
	    lila1.addView(SendMessage);	    
	    lila1.addView(message);
	    alert.setView(lila1);

		alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String sendTo = to.getText().toString();
		  String messageBody = message.getText().toString();
		  if (sendTo.equals("") || sendTo.equals(null)){
				Context context = getApplicationContext();
				CharSequence text = "Enter a Username to send message to";
				int duration = Toast.LENGTH_SHORT;
			
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
		  }
		  else{
			  new SendMessageTask().execute(sendTo,messageBody);
			  MessengerDataSource mds2 = new MessengerDataSource(MainActivity.this);
				
				mds2.open();
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date();
				
				
				
				try {
					mds2.insertMessage(mds2.getUsername(), sendTo, "Me: " + messageBody, format.format(date));
				} catch (Exception e) {
					System.out.println("Insert Failed");
					e.printStackTrace();
				}
				
				mds2.close();
				final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
				if(spinner.getSelectedItemPosition()==0){
                	populateSaved();
                }
		  }
		  
		  }
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Cancelled.
		  }
		});

		alert.show();
		
	}
	
	//Get Login Info
	private class Logout extends AsyncTask<Void, Void, String>{
		@Override
		protected String doInBackground(Void... nothing) {
			
			MessengerDataSource mds2 = new MessengerDataSource(MainActivity.this);
			
			mds2.open();
			
			try {
				mds2.logoutUser();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mds2.close();
			
			return "";
		}
		
		@Override
		protected void onPostExecute(String whatever) {
				Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
				startActivityForResult(myIntent, 0);
				MainActivity.this.finish();
		}
		
	}
	
	private void populateSaved(){
		saveFlag = true;
		fullList = new ArrayList<Messages>();
		MessengerDataSource mds = new MessengerDataSource(MainActivity.this);
		mds.open();
		Cursor messages = mds.getMessages();
		for(int i = 0; i < messages.getCount(); i++){
			messages.moveToPosition(i);
			
			int idIdx = messages.getColumnIndex(MessengerSQLiteHelper.COLUMN_ID),
					userIdx = messages.getColumnIndex(MessengerSQLiteHelper.COLUMN_USERNAME),
					senderIdx = messages.getColumnIndex(MessengerSQLiteHelper.COLUMN_SENDER),
					msgIdx = messages.getColumnIndex(MessengerSQLiteHelper.COLUMN_MESSAGE),
					timeIdx = messages.getColumnIndex(MessengerSQLiteHelper.COLUMN_TIME);
			

			fullList.add(new Messages(messages.getString(userIdx),messages.getString(senderIdx),
					messages.getString(timeIdx),messages.getString(msgIdx),idIdx));
			
		}
		mds.close();
		
		ListView list = (ListView) findViewById(R.id.mainListView);
		MessagesAdapter ad = new MessagesAdapter(this,fullList);
		list.setAdapter(ad);
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
                Intent messageIntent = new Intent(MainActivity.this, ViewMessage.class);
                Messages mes = new Messages();
                mes = fullList.get(position);

                messageIntent.putExtra(VIEW2, view2);

                messageIntent.putExtra("message", mes);

                startActivity(messageIntent);
                
            }
        });

	}
	
	
	private void populateNew(){

		  new GetMessageTask().execute();
		
	}

	public class GetMessageTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("receiver", username));
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_GET);
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					
				}
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String resp){

			 
			try {

				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(new ByteArrayInputStream(resp.getBytes()));
				
				 
				doc.getDocumentElement().normalize();
			 
			 
				NodeList nList = doc.getElementsByTagName("message");

				fullList = new ArrayList<Messages>();
			 
				for (int i = 0; i < nList.getLength(); i++) {
					
					Node nNode = nList.item(i);
			 
					if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			 
						Element ele = (Element) nNode;
						
						String msgtxt = ele.getTextContent();
						String from = ele.getAttribute("from");
						String time = ele.getAttribute("datetime");
						fullList.add(new Messages(username,from,time,msgtxt,i));
			 
					}
				}
				saveFlag = false;
				ListView list = (ListView) findViewById(R.id.mainListView);
				MessagesAdapter ad = new MessagesAdapter(MainActivity.this,fullList);
				list.setAdapter(ad);
		        list.setOnItemClickListener(new OnItemClickListener() {
		            public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
		                Intent messageIntent = new Intent(MainActivity.this, ViewMessage.class);
		                Messages mes = new Messages();
		                mes = fullList.get(position);
		                messageIntent.putExtra("message", mes);
		                
		                messageIntent.putExtra(VIEW2, view2);
		                //messageIntent.putExtra(EXTRA_MESSAGE, listOfMessages.get(position).getID());
		                startActivity(messageIntent);
		                
		            }
		        });
				
			} catch (Exception e) {
				e.printStackTrace();
		    }
		}
	}

	public class SendMessageTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			String response="false";
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("touser", params[0]));
				n.add(new BasicNameValuePair("fromuser", username));
				n.add(new BasicNameValuePair("message", params[1]));
				
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_SEND);
				
				
				
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					
				}
			}
			
			return response;
		}
		
		@Override
		protected void onPostExecute(String whatever) {
			if(!whatever.equals("false")){
				Context context = getApplicationContext();
				CharSequence text = "Message Sent!";
				int duration = Toast.LENGTH_SHORT;
			
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
				
			}
			else{
				Context context = getApplicationContext();
				CharSequence text = "User does not exist!";
				int duration = Toast.LENGTH_SHORT;
			
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
		}
	}

	public class CheckMessageTask extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			// TODO: attempt authentication against a network service.
			String response = "";
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("user", username));
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_CHECK);
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					response = httpClient.execute(httppost, respondHandler);
				}
				catch(Exception e){
					
				}
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String resp){
			if(resp.contains("true")){
				Context context = getApplicationContext();
				CharSequence text = "New Messages";
				int duration = Toast.LENGTH_SHORT;
			
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
		}
		
	}

}


